//
//  KATRadioButton.m
//  KATFramework
//
//  Created by Kantice on 14-6-24.
//  Copyright (c) 2014年 KatApp. All rights reserved.
//

#import "KATRadioButton.h"

@implementation KATRadioButton

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/



+ (instancetype)buttonWithFrame:(CGRect)frame
{
    KATRadioButton *radioButton=[[[self alloc] init] autorelease];
        
    radioButton.frame=frame;
    
    radioButton.lineWidth=0.5;
    radioButton.cornerRadius=5.0f;
    radioButton.color=KCOLOR_BLUE;
    radioButton.lightColor=[UIColor whiteColor];
    radioButton.backgroundColor=[UIColor clearColor];
    radioButton.clipsToBounds=YES;
    radioButton.labelFont=[UIFont systemFontOfSize:frame.size.height*0.48];
    radioButton.buttonHeight=frame.size.height*0.62;
    radioButton.buttonLineWidth=1.0f;
    radioButton.selectedIndex=-1;
    radioButton.lastIndex=-1;
    
    return radioButton;
}



- (int)itemCount
{
    if(_items)
    {
        return _items.length;
    }
    
    return 0;
}



- (void)loadItems:(KATArray<__kindof KATRadioButtonItem *> *)items
{
    if(items && items.length>0)
    {
        //删除之前的内容
        for(UIView *view in self.subviews)
        {
            [view removeFromSuperview];
        }
        
        self.items=items;
        
        self.layer.borderWidth=_lineWidth;
        self.layer.borderColor=_color.CGColor;
        self.backgroundColor=[UIColor clearColor];
        self.layer.cornerRadius=_cornerRadius;
        self.selectedIndex=0;
        
        //清空之前的容器数组
        if(!_views)
        {
            self.views=[KATArray arrayWithCapacity:_items.length];
        }
        else
        {
            [_views clear];
        }
        
        //清空之前的标签数组
        if(!_labels)
        {
            self.labels=[KATArray arrayWithCapacity:_items.length];
        }
        else
        {
            [_labels clear];
        }
        
        //清空之前的按钮数组
        if(!_buttons)
        {
            self.buttons=[KATArray arrayWithCapacity:_items.length];
        }
        else
        {
            [_buttons clear];
        }
        
        //遍历数组
        for(int i=0;i<_items.length;i++)
        {
            KATRadioButtonItem *item=(KATRadioButtonItem *)[_items get:i];
            item.index=i;
            
            //选中的项目
            if(i==_selectedIndex)
            {
                self.selectedItem=item;
            }
            
            //背景容器
            UIView *view=[[[UIView alloc] init] autorelease];
            view.frame=CGRectMake(self.frame.size.width/_items.length*i, 0, self.frame.size.width/_items.length, self.frame.size.height);
            view.layer.borderWidth=_lineWidth*0.5;
            view.layer.borderColor=_color.CGColor;
            view.backgroundColor=[UIColor clearColor];
            view.tag=i;
            [self addSubview:view];
            
            UITapGestureRecognizer *singleTap=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(itemTap:)];
            singleTap.numberOfTapsRequired=1;
            [view addGestureRecognizer:singleTap];
            [singleTap release];
            singleTap=nil;
            
            [self.views put:view];
            
            if(!item.hasButton && item.hasLabel)//纯文本
            {
                UILabel *label=[[[UILabel alloc] init] autorelease];
                
                label.frame=CGRectMake(view.frame.size.width*0.08, 0, view.frame.size.width*0.84, view.frame.size.height);
                label.text=item.label;
                label.tag=i;
                label.textAlignment=NSTextAlignmentCenter;
                label.numberOfLines=1;
                label.lineBreakMode=NSLineBreakByTruncatingTail;
                label.userInteractionEnabled=YES;
                label.textColor=_color;
                label.font=_labelFont;
                label.backgroundColor=[UIColor clearColor];
                
                [view addSubview:label];
                [self.labels put:label];
            }
            else if(item.hasButton && !item.hasLabel)//纯按钮
            {
                KATButton *button=[KATButton buttonWithFrame:CGRectMake((view.frame.size.width-_buttonHeight)*0.5, (view.frame.size.height-_buttonHeight)*0.5, _buttonHeight, _buttonHeight) type:item.button color:_color lineWidth:_buttonLineWidth scale:1.0 andOnClickAction:nil];
                button.tag=i;
                
                [view addSubview:button];
                [self.buttons put:button];
            }
            else if(item.hasButton && item.hasLabel)//既有文本又有按钮
            {
                //标签
                UILabel *label=[[[UILabel alloc] init] autorelease];
                
                label.text=item.label;
                label.tag=i;
                label.textAlignment=NSTextAlignmentCenter;
                label.numberOfLines=1;
                label.lineBreakMode=NSLineBreakByTruncatingTail;
                label.userInteractionEnabled=YES;
                label.textColor=_color;
                label.font=_labelFont;
                label.backgroundColor=[UIColor clearColor];
                
                [view addSubview:label];
                [self.labels put:label];
                
                
                
                
                float textWidth=view.frame.size.width*(1-0.08*2-0.04)-_buttonHeight;//文本宽度
                
                //计算文本尺寸
//                CGSize size=[item.label sizeWithFont:label.font constrainedToSize:CGSizeMake(CGFLOAT_MAX,view.frame.size.height*0.7) lineBreakMode:NSLineBreakByCharWrapping];
                
                CGSize size=[item.label boundingRectWithSize:CGSizeMake(CGFLOAT_MAX,view.frame.size.height*0.7) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:label.font} context:nil].size;
                
                if(size.width<textWidth)//比最大宽度小
                {
                    textWidth=size.width;
                }
                
                float padding=view.frame.size.width*0.08+(view.frame.size.width*0.8-_buttonHeight-textWidth)*0.5;//计算边距
                
                
                if(item.isButtonOnRight)//按钮右侧模式
                {
                    //按钮
                    KATButton *button=[KATButton buttonWithFrame:CGRectMake(padding+textWidth+view.frame.size.width*0.04, (view.frame.size.height-_buttonHeight)*0.5, _buttonHeight, _buttonHeight) type:item.button color:_color lineWidth:_buttonLineWidth scale:1.0 andOnClickAction:nil];
                    button.tag=i;
                    
                    [view addSubview:button];
                    [self.buttons put:button];
                    
                    
                    label.frame=CGRectMake(padding, 0, textWidth, view.frame.size.height);
                }
                else
                {
                    //按钮
                    KATButton *button=[KATButton buttonWithFrame:CGRectMake(padding, (view.frame.size.height-_buttonHeight)*0.5, _buttonHeight, _buttonHeight) type:item.button color:_color lineWidth:_buttonLineWidth scale:1.0 andOnClickAction:nil];
                    button.tag=i;
                    
                    [view addSubview:button];
                    [self.buttons put:button];
                    
                    
                    label.frame=CGRectMake(padding+_buttonHeight+view.frame.size.width*0.04, 0, textWidth, view.frame.size.height);
                }
                
            }
            
            [self updateItems];
        }
    }
}






- (void)itemTap:(UITapGestureRecognizer *)recognizer
{
    _lastIndex=_selectedIndex;//上次选中的标签，为了判断是否重复点击
    
    _selectedIndex=(int)recognizer.view.tag;
    
    if(_lastIndex!=_selectedIndex)//避免重复点击事件
    {
        [self updateItems];
        
        if(_eventDelegate && [_eventDelegate respondsToSelector:@selector(radioButton:didChangedSelectedItem:)])
        {
            [_eventDelegate radioButton:self didChangedSelectedItem:_selectedItem];
        }
    }
}


- (void)changeSelectedIndex:(int)index
{
    if(_items && _items.length>0)
    {
        if(index>=0 && index<_items.length)
        {
            _selectedIndex=index;
            
            [self updateItems];
        }
    }
}


- (void)changeSelectedItem:(KATRadioButtonItem *)item
{
    if(item && _items && _items.length>0)
    {
        int index=-1;
        
        for(int i=0;i<_items.length;i++)
        {
            if(item==[_items get:i])
            {
                index=i;
                
                break;
            }
        }
        
        if(index>=0)
        {
            [self changeSelectedIndex:index];
        }
    }
}


- (void)updateItems
{
    if(_items && _items.length>0)
    {
        if(_selectedIndex<0 || _selectedIndex>=_items.length)
        {
            _selectedIndex=0;
        }
        
        //选择项目
        self.selectedItem=(KATRadioButtonItem *)[_items get:_selectedIndex];
        
        //更新背景容器
        if(_views && _views.length>0)
        {
            for(int i=0;i<_views.length;i++)
            {
                UIView *view=(UIView *)[_views get:i];
                
                if(view)
                {
                    if(view.tag==_selectedIndex)//选中
                    {
                        view.backgroundColor=_color;
                    }
                    else//未选中
                    {
                        view.backgroundColor=[UIColor clearColor];
                    }
                }
            }
        }
        
        //更新标签
        if(_labels && _labels.length>0)
        {
            for(int i=0;i<_labels.length;i++)
            {
                UILabel *label=(UILabel *)[_labels get:i];
                
                if(label)
                {
                    if(label.tag==_selectedIndex)//选中
                    {
                        label.textColor=_lightColor;
                    }
                    else//未选中
                    {
                        label.textColor=_color;
                    }
                }
            }
        }
        
        //更新按钮
        if(_buttons && _buttons.length>0)
        {
            for(int i=0;i<_buttons.length;i++)
            {
                KATButton *button=(KATButton *)[_buttons get:i];
                
                if(button)
                {
                    if(button.tag==_selectedIndex)//选中
                    {
                        button.color=_lightColor;
                    }
                    else//未选中
                    {
                        button.color=_color;
                    }
                }
            }
        }
        
    }
    
}


//更换颜色
- (void)changeColor:(UIColor *)color
{
    self.color=color;
    self.layer.borderColor=_color.CGColor;
    
    [self updateItems];
}


- (void)dealloc
{
    [_color release];
    [_lightColor release];
    [_labels release];
    [_labelFont release];
    [_buttons release];
    [_items release];
    [_views release];
    [_selectedItem release];
    
    [super dealloc];
}


@end
